package com.cicigodd.brick.plug.system.role.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cicigodd.brick.plug.common.exception.BusinessException;
import com.cicigodd.brick.plug.common.factory.PageFactory;
import com.cicigodd.brick.plug.common.factory.PageResultFactory;
import com.cicigodd.brick.plug.common.response.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cicigodd.brick.plug.system.role.entity.SysRole;
import com.cicigodd.brick.plug.system.role.request.*;
import com.cicigodd.brick.plug.system.role.response.SysRoleDetailResponse;
import com.cicigodd.brick.plug.system.role.response.SysRoleListResponse;
import com.cicigodd.brick.plug.system.role.mapper.SysRoleMapper;
import com.cicigodd.brick.plug.system.role.service.SysRoleMenuService;
import com.cicigodd.brick.plug.system.role.service.SysRoleService;
import com.cicigodd.brick.plug.system.role.service.SysRoleUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 角色管理
 *
 * @author cicigodd
 * @date 2022/12/12 15:52:23
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysRoleUserService sysRoleUserService;

    /**
     * 添加
     *
     * @author cicigodd
     * @date 2022/12/12 15:52:23
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysRoleAddRequest sysRoleAddRequest) {
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRole::getRoleCode,sysRoleAddRequest.getRoleCode());
        SysRole role = this.getOne(lambdaQueryWrapper);
        if(ObjectUtil.isNotNull(role)){
            throw new BusinessException("此角色code已存在！");
        }
        SysRole sysRole = new SysRole();
        BeanUtil.copyProperties(sysRoleAddRequest, sysRole);
        this.save(sysRole);
        //保存角色菜单管理
        List<Integer> menuIds = sysRoleAddRequest.getMenuIds();
        menuIds.forEach(menuId -> {
            SysRoleMenuAddRequest sysRoleMenuAddRequest = new SysRoleMenuAddRequest();
            sysRoleMenuAddRequest.setRoleId(sysRole.getId());
            sysRoleMenuAddRequest.setMenuId(menuId);
            sysRoleMenuService.add(sysRoleMenuAddRequest);
        });
    }

    /**
     * 删除
     *
     * @author cicigodd
     * @date 2022/12/12 15:52:23
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(SysRoleDeleteRequest sysRoleDeleteRequest) {
        this.removeByIds(sysRoleDeleteRequest.getIds());
    }


    /**
     * 编辑
     *
     * @author cicigodd
     * @date 2022/12/12 15:52:23
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(SysRoleEditRequest sysRoleEditRequest) {
        SysRole sysRole = this.getById(sysRoleEditRequest.getId());
        if (ObjectUtil.isEmpty(sysRole)) {
            throw new BusinessException("查询结果不存在");
        }
        //角色code不能修改
        sysRoleEditRequest.setRoleCode(sysRole.getRoleCode());
        BeanUtil.copyProperties(sysRoleEditRequest, sysRole);
        this.updateById(sysRole);
        //删除当前角色绑定的菜单
        sysRoleMenuService.deleteByRoleId(sysRole.getId());
        //保存角色菜单管理
        List<Integer> menuIds = sysRoleEditRequest.getMenuIds();
        menuIds.forEach(menuId -> {
            SysRoleMenuAddRequest sysRoleMenuAddRequest = new SysRoleMenuAddRequest();
            sysRoleMenuAddRequest.setRoleId(sysRole.getId());
            sysRoleMenuAddRequest.setMenuId(menuId);
            sysRoleMenuService.add(sysRoleMenuAddRequest);
        });
    }

    /**
     * 详情
     *
     * @author cicigodd
     * @date 2022/12/12 15:52:23
     */
    @Override
    public SysRoleDetailResponse detail(SysRoleDetailRequest sysRoleDetailRequest) {
        SysRole sysRole = this.getById(sysRoleDetailRequest.getId());
        if (ObjectUtil.isEmpty(sysRole)) {
            throw new BusinessException("查询结果不存在");
        }
        SysRoleDetailResponse sysRoleDetailResponse = new SysRoleDetailResponse();
        BeanUtil.copyProperties(sysRole, sysRoleDetailResponse);
        return sysRoleDetailResponse;
    }

    /**
     * 列表
     *
     * @author cicigodd
     * @date 2022/12/12 15:52:23
     */
    @Override
    public PageResult<SysRoleListResponse> list(SysRoleListRequest sysRoleListRequest) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        String roleCode = sysRoleListRequest.getRoleCode();
        String roleName = sysRoleListRequest.getRoleName();
        Integer sort = sysRoleListRequest.getSort();
        String statusFlag = sysRoleListRequest.getStatusFlag();

        wrapper.like(ObjectUtil.isNotEmpty(roleCode), SysRole::getRoleCode, roleCode);
        wrapper.like(ObjectUtil.isNotEmpty(roleName), SysRole::getRoleName, roleName);
        wrapper.like(ObjectUtil.isNotEmpty(statusFlag), SysRole::getStatusFlag, statusFlag);
        wrapper.eq(ObjectUtil.isNotNull(sort), SysRole::getSort, sort);
        IPage<SysRoleListResponse> page = this.page(PageFactory.defaultPage(sysRoleListRequest.getPageNum(),sysRoleListRequest.getPageSize()), wrapper).convert(SysRole -> BeanUtil.copyProperties(SysRole, SysRoleListResponse.class));
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public List<SysRoleListResponse> listAll(SysRoleListRequest sysRoleListRequest) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        String roleCode = sysRoleListRequest.getRoleCode();
        String roleName = sysRoleListRequest.getRoleName();
        Integer sort = sysRoleListRequest.getSort();

        wrapper.like(ObjectUtil.isNotEmpty(roleCode), SysRole::getRoleCode, roleCode);
        wrapper.like(ObjectUtil.isNotEmpty(roleName), SysRole::getRoleName, roleName);
        wrapper.eq(ObjectUtil.isNotNull(sort), SysRole::getSort, sort);
        List<SysRole> list = this.list(wrapper);
        return BeanUtil.copyToList(list,SysRoleListResponse.class);
    }

    @Override
    public List<Integer> getMenuIdsByRoleId(Integer roleId) {
        return sysRoleMenuService.getMenuIdsByRoleId(roleId);
    }

    /**
     * 根据userId获取角色标识
     * @param userId
     * @return
     */
    @Override
    public List<String> getRolesByUserId(Integer userId) {
        List<Integer> roleIds = sysRoleUserService.getRoleIdsByUserId(userId);
        List<SysRole> sysRoles = this.listByIds(roleIds);
        List<String> list = sysRoles.stream().map(SysRole::getRoleCode).collect(Collectors.toList());
        return list;
    }

    /**
     * 根据userId获取权限标识
     * @param userId
     * @return
     */
    @Override
    public List<String> getPermsByUserId(Integer userId) {
        List<Integer> roleIds = sysRoleUserService.getRoleIdsByUserId(userId);
        return sysRoleMenuService.getPermsIdsByRoleIds(roleIds);
    }

    /**
     * 根据角色code 获取角色id
     * @param roleCode
     * @return
     */
    @Override
    public Integer getRoleIdByRoleCode(String roleCode) {
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRole::getRoleCode,roleCode);
        SysRole role = this.getOne(lambdaQueryWrapper);
        return role.getId();
    }
}
